<template>
  <el-button type="success" round style="float: right" @click="addOneType()" v-permission="'knowledgeType.add'">
    添加一级分类
  </el-button>
  <!-- <el-input
    v-model="query"
    placeholder="请输入关键字"
    @input="onQueryChanged"
    style="width: 350px;"
  /> -->
  <el-table
      :data="data"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasCn' }"
      :highlight-current-row="true"
    >
      <el-table-column
        prop="flmc"
        label="名称"
        width="450"
      ></el-table-column>
      <el-table-column
        prop="bz"
        label="备注"
        width="180"
      ></el-table-column>
      <el-table-column label="操作" fixed="right" >
        <template #default="{ row }">
          <el-link type="success" v-if="row.fljb<3"  @click="append(row.id)" v-permission="'knowledgeType.add'">添加子类</el-link>
          <el-link type="primary" @click="edit(row.id)" v-permission="'knowledgeType.update'">编辑</el-link>
          <el-link type="danger" @click="remove(row)" v-if="row.children==null" v-permission="'knowledgeType.delete'">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
<!--   <el-tree-v2
    ref="treeRef"
    :data="data"
    :props="props"
    :filter-method="filterMethod"
    :height="300"
    :highlight-current="true"
    v-loading="loading"
  >
    <template #default="{ node }">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <el-tooltip
          class="box-item"
          effect="dark"
          :content="node.data.bz"
          placement="right"
        >
          <span>{{ node.label }}</span>
        </el-tooltip>
        <span>
          最多添加到3级
          <el-link type="success" v-if="node.data.fljb<3"  @click="append(node)" v-permission="'knowledgeType.add'">添加子类</el-link>
          <el-link type="primary" @click="edit(node)" v-permission="'knowledgeType.update'">编辑</el-link>
          <el-link type="danger" @click="remove(node)" v-if="node.isLeaf" v-permission="'knowledgeType.delete'">
            删除
          </el-link>
        </span>
      </span>
    </template>
  </el-tree-v2> -->

  <!-- 添加修改对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="dialogType + '知识分类'">
    <el-form
      :model="form"
      label-position="right"
      label-width="120px"
      ref="ruleFormRef"
      :rules="rules"
    >
      <el-form-item label="知识分类名称" prop="ktypeName">
        <el-input v-model="form.flmc" autocomplete="off" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.bz" autocomplete="off" />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup >
import { onMounted, reactive, ref } from 'vue'
import type { TreeNode } from 'element-plus/es/components/tree-v2/src/types'
import {
  getTreeApi,
  deleteTypeApi,
  updateTypeApi,
  getInfoApi,
  saveTypeApi,
} from '@/api/knowledgeBase/typeTree.js'
import { create } from 'domain'
import {
  ElMessage,
  ElMessageBox,
  ElTreeV2,
  FormInstance,
  FormRules,
} from 'element-plus'

const ruleFormRef = ref<FormInstance>()
const data = ref([])
const dialogFormVisible = ref(false)
const dialogType = ref('')
const form = ref({
  id: null,
  sjflid: null,
  flmc: '',
  bz: '',
})

const query = ref('')
const treeRef = ref<InstanceType<typeof ElTreeV2>>()
const loading = ref(true)
// 表单校验
const rules = reactive<FormRules>({
  flmc: [{ required: true, message: '知识分类名称不能为空', trigger: 'blur' }],
})

// 属性映射
const props = {
  value: 'id',
  label: 'flmc',
  children: 'children',
}

// 过滤搜索时调用
const onQueryChanged = (query: string) => {
  treeRef.value!.filter(query)
}
const filterMethod = (query: string, node) => {
  return node.flmc.includes(query)
}

// 清空表单
const clearForm = () => {
    (form.value.id = null),
    (form.value.flmc = ''),
    (form.value.bz = ''),
    (form.value.sjflid = null)
}

// 修改或添加
const saveOrUpdate = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(valid => {
    if (valid) {
      dialogFormVisible.value = false

      if (form.value.id == null) {
        console.log('这个添加操作' + JSON.stringify(form.value))
        saveTypeApi({
          sjflid: form.value.sjflid,
          flmc: form.value.flmc,
          bz: form.value.bz,
        }).then(res => {
          // 关闭对话框
          dialogFormVisible.value = false
          // 提示成功
          ElMessage({
            type: 'success',
            message: '添加成功！！！！',
          })

          // 刷新树
          getData()

          dialogType.value = ''
        })
      } else {
        console.log('这是修改操作：' + JSON.stringify(form.value))
        updateTypeApi({
          id: form.value.id,
          flmc: form.value.flmc,
          bz: form.value.bz,
        }).then(res => {
          // 关闭对话框
          dialogFormVisible.value = false
          // 提示成功
          ElMessage({
            type: 'success',
            message: '修改成功！！！！',
          })

          // 刷新树
          getData()

          dialogType.value = ''
        })
      }
    } else {
      return false
    }
  })
}
// 点击添加一级分类
const addOneType = () => {
  // 清空表单
  clearForm()

  // 设置父分类id
  form.value.sjflid = 0
  dialogType.value = '添加'
  // 显示对话框
  dialogFormVisible.value = true
}

// 点击添加
const append = currentId => {
  // 清空表单
  clearForm()

  // 设置父分类id
  form.value.sjflid = currentId

  dialogType.value = '添加'
  // 显示对话框
  dialogFormVisible.value = true
}
// 点击修改
const edit = currentId => {
  // 清空表单
  clearForm()

  // 根据id获取数据
  getInfoApi(currentId).then(res => {
    form.value = res.data
    dialogType.value = '修改'
    dialogFormVisible.value = true
  })
}

// 点击删除
const remove = node => {
  // 确认是否删除
  ElMessageBox.confirm(`确认是否删除【${node.flmc}】?`, {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteTypeApi([node.id])
        .then(res => {
          ElMessage({
            type: 'success',
            message: '删除成功！！！！',
          })

          // 刷新树
          getData()
        })
        .catch(e => {
          ElMessage({
            type: 'error',
            message: '删除失败！！！！',
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除！！！！',
      })
    })
}

// 获取分类树
const getData = async () => {
  const res = await getTreeApi()
  data.value = res.data
  loading.value = false
}

onMounted(() => {
  getData()
})
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-link {
  margin-right: 8px;
}
.el-link .el-icon--right.el-icon {
  vertical-align: text-bottom;
}
.tooltip-base-box {
  width: 600px;
}
.tooltip-base-box .row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.tooltip-base-box .center {
  justify-content: center;
}
.tooltip-base-box .box-item {
  width: 110px;
  margin-top: 10px;
}
</style>